home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 2 / Apprentice-Release2.iso / Information / Languages / C++ / C++ FAQ 1⁄4 next >
Encoding:
Internet Message Format  |  1994-12-08  |  48.6 KB  |  [TEXT/R*ch]

  1. Path: bloom-beacon.mit.edu!gatech!howland.reston.ans.net!pipex!uunet!library.erc.clarkson.edu!sun.soe.clarkson.edu!cline
  2. From: cline@sun.soe.clarkson.edu (Marshall Cline)
  3. Newsgroups: comp.lang.c++
  4. Subject: C++ FAQ: posting #1/4
  5. Followup-To: comp.lang.c++
  6. Date: 14 Nov 1994 00:26:13 GMT
  7. Organization: Paradigm Shift, Inc (training/consulting/OOD/OOP/C++)
  8. Lines: 1070
  9. Sender: cline@sun.soe.clarkson.edu
  10. Distribution: world
  11. Expires: +1 month
  12. Message-ID: <3a6ar5$gd6@library.erc.clarkson.edu>
  13. Reply-To: cline@parashift.com (Marshall Cline)
  14. NNTP-Posting-Host: sun.soe.clarkson.edu
  15. Summary: Please read this before posting to comp.lang.c++
  16.  
  17. comp.lang.c++ Frequently Asked Questions list (with answers, fortunately).
  18. Copyright (C) 1991-94 Marshall P. Cline, Ph.D.
  19. Posting 1 of 4.
  20.  
  21. UPDATED 11/94:
  22.  * Added differentiator between "FAQ book" and "FAQ posting"
  23.  * Other cosmetic changes
  24.  
  25. UPDATED 10/94:
  26.  * Fixed a few typos
  27.  
  28. UPDATED 9/94:
  29.  * Minor cosmetic changes
  30.  
  31. UPDATED 8/94:
  32.  * Made it up-to-date with respect to "typeid" and "dynamic_cast".
  33.  * Made it up-to-date with respect to "mutable" and "const_cast".
  34.  * Rewrote most of the answers to provide general cleanup.
  35.  * The quotation marks are now "..." rather than `...' or ``...''
  36.  * Sample code lines start with a tab; no other lines starts with a tab.
  37.  * Everything was edited; minor modifications everywhere.
  38.  
  39. ==============================================================================
  40. SECTION 1: Introduction and table of contents
  41. ==============================================================================
  42.  
  43.     DOCUMENT:    Frequently-Asked-Questions for comp.lang.c++
  44.     REVISION:    Nov 13, 1994
  45.  
  46.     POSTING!=BOOK:    This C++ FAQ posting is NOT the same as the "FAQ book".
  47.             The "FAQ book" ("C++ FAQs", Addison-Wesley, 1995) is
  48.             5x larger than this posting.  See below for more.
  49.  
  50.     AUTHOR:        Marshall P. Cline, Ph.D.
  51.             Paradigm Shift, Inc.
  52.             One Park St. / Norwood, NY  13668
  53.             voice: 315-353-6100
  54.             fax:   315-353-6110
  55.             email: cline@parashift.com
  56.  
  57.     COPYRIGHT:    Copyright (C), 1991-94 Marshall P. Cline, Ph.D.
  58.             Permission to copy all or part of this work is granted,
  59.             provided that the copies are not made or distributed
  60.             for resale (except a nominal copy fee may be charged),
  61.             and provided that the AUTHOR, COPYRIGHT, & NO WARRANTY
  62.             sections are retained verbatim and are displayed
  63.             conspicuously.  If anyone needs other permissions that
  64.             aren't covered by the above, please contact the author.
  65.  
  66.     NO WARRANTY:    THIS WORK IS PROVIDED ON AN "AS IS" BASIS.  THE AUTHOR
  67.             PROVIDES NO WARRANTY WHATSOEVER, EITHER EXPRESS OR
  68.             IMPLIED, REGARDING THE WORK, INCLUDING WARRANTIES WITH
  69.             RESPECT TO ITS MERCHANTABILITY OR FITNESS FOR ANY
  70.             PARTICULAR PURPOSE.
  71.  
  72.     AVAILABILITY:    This is available via anonymous ftp
  73.             from: sun.soe.clarkson.edu [128.153.12.3]
  74.             in the file: pub/C++/FAQ
  75.             URL:  ftp://sun.soe.clarkson.edu/pub/C++/FAQ
  76.  
  77.     WITHOUT FTP:    You can also get it by sending electronic mail:
  78.             |    To: archive-server@sun.soe.clarkson.edu
  79.             |    Subject: send C++/FAQ
  80.             This will help those who don't have ftp.
  81.         (note: I hear the mail server is down; if you have problems,
  82.                send details and I'll look into it).
  83.  
  84.     SEE ALSO:    comp.lang.c FAQ appears every month in that newsgroup,
  85.             and is maintained by Steve Summit (scs@eskimo.com).
  86.  
  87. ==============================================================================
  88. SUBSECTION 1A: "FAQ book" versus "FAQ posting"
  89. ==============================================================================
  90.  
  91. Now that Addison-Wesley has published "C++ FAQs" by Cline and Lomow (1995,
  92. ISBN 0-201-58958-3), many people have asked about the relationship between the
  93. book and this posting.  Some who haven't seen the book have wondered whether
  94. the posting was equivalent to the book.  This section answers these questions.
  95.  
  96. The "FAQ book" (at bookstores starting Oct. 94) is loosely based on the same
  97. concepts as this posting.  However the FAQ book is approx five (5) times
  98. bigger than this posting, including thousands of cross references, external
  99. references, and index terms, as well as many programming examples.
  100.  
  101. ==============================================================================
  102. SUBSECTION 1B: Table of Contents
  103. ==============================================================================
  104.  
  105. ========== POSTING #1 ==========
  106.  
  107. SECTION 1: Introduction and table of contents
  108. SUBSECTION 1A: "FAQ book" versus "FAQ posting"
  109. SUBSECTION 1B: Table of Contents
  110. SUBSECTION 1C: Nomenclature and Common Abbreviations
  111.  
  112. SECTION 2: How should I post something? (READ BEFORE POSTING)
  113. Q1: Which newsgroup should I post my questions?
  114. Q2: How do I post a question about code that doesn't work correctly?
  115.  
  116. SECTION 3: Environmental/managerial issues
  117. Q3: What is OOP?  What is C++?
  118. Q4: What are some advantages of C++?
  119. Q5: Who uses C++?
  120. Q6: Are there any C++ standardization efforts underway?
  121. Q7: Where can I get a copy of the latest ANSI-C++ draft standard?
  122. Q8: Is C++ backward compatible with ANSI-C?
  123. Q9: How long does it take to learn C++?
  124.  
  125. SECTION 4: Basics of the paradigm
  126. Q10: What is a class?
  127. Q11: What is an object?
  128. Q12: What is a reference?
  129. Q13: What happens if you assign to a reference?
  130. Q14: How can you reseat a reference to make it refer to a different object?
  131. Q15: When should I use references, and when should I use pointers?
  132. Q16: What's the deal with inline functions?
  133.  
  134. SECTION 5: Constructors and destructors
  135. Q17: What's the deal with constructors?
  136. Q18: How can I make a constructor call another constructor as a primitive?
  137. Q19: What's the deal with destructors?
  138.  
  139. SECTION 6: Operator overloading
  140. Q20: What's the deal with operator overloading?
  141. Q21: What operators can/cannot be overloaded?
  142. Q22: Can I create a "**" operator for "to-the-power-of" operations?
  143.  
  144. SECTION 7: Friends
  145. Q23: What is a "friend"?
  146. Q24: Do "friends" violate encapsulation?
  147. Q25: What are some advantages/disadvantages of using friend functions?
  148. Q26: What does it mean that "friendship is neither inherited nor transitive"?
  149. Q27: Should my class declare a member function or a friend function?
  150.  
  151. SECTION 8: Input/output via <iostream.h> and <stdio.h>
  152. Q28: How can I provide printing for a "class Fred"?
  153. Q29: Why should I use <iostream.h> instead of the traditional <stdio.h>?
  154.  
  155. ========== POSTING #2 ==========
  156.  
  157. SECTION 9: Freestore management
  158. Q30: Does "delete p" delete the pointer "p", or the pointed-to-data, "*p"?
  159. Q31: Can I "free()" pointers allocated with "new"?  Can I "delete" pointers
  160.    alloc'd with "malloc()"?
  161. Q32: Why should I use "new" instead of trustworthy old malloc()?
  162. Q33: Why doesn't C++ have a "realloc()" along with "new" and "delete"?
  163. Q34: How do I allocate / unallocate an array of things?
  164. Q35: What if I forget the "[]" when "delete"ing array allocated via "new
  165.    Fred[n]"?
  166.  
  167. SECTION 10: Debugging and error handling
  168. Q36: How can I handle a constructor that fails?
  169. Q37: How should I handle resources if my constructors may throw exceptions?
  170.  
  171. SECTION 11: Const correctness
  172. Q38: What is "const correctness"?
  173. Q39: Should I try to get things const correct "sooner" or "later"?
  174. Q40: What is a "const member function"?
  175. Q41: What do I do if I want to update an "invisible" data member inside a
  176.    "const" member function?
  177. Q42: Does "const_cast" mean lost optimization opportunities?
  178.  
  179. SECTION 12: Inheritance
  180. Q43: Is inheritance important to C++?
  181. Q44: When would I use inheritance?
  182. Q45: How do you express inheritance in C++?
  183. Q46: Is it ok to convert a pointer from a derived class to its base class?
  184. Q47: Derived* --> Base* works ok; why doesn't Derived** --> Base** work?
  185. Q48: Does array-of-Derived is-NOT-a-kind-of array-of-Base mean arrays are
  186.    bad?
  187. SUBSECTION 12A: Inheritance -- Virtual functions
  188. Q49: What is a "virtual member function"?
  189. Q50: How can C++ achieve dynamic binding yet also static typing?
  190. Q51: Should a derived class replace ("override") a non-virtual fn from a base
  191.    class?
  192. Q52: What's the meaning of, "Warning: Derived::f(int) hides Base::f(float)"?
  193. SUBSECTION 12B: Inheritance -- Conformance
  194. Q53: Should I hide public member fns inherited from my base class?
  195. Q54: Is a "Circle" a kind-of an "Ellipse"?
  196. Q55: Are there other options to the "Circle is/isnot kind-of Ellipse"
  197.    dilemma?
  198. SUBSECTION 12C: Inheritance -- Access rules
  199. Q56: Why can't my derived class access "private" things from my base class?
  200. Q57: What's the difference between "public:", "private:", and "protected:"?
  201. Q58: How can I protect subclasses from breaking when I change internal parts?
  202. SUBSECTION 12D: Inheritance -- Constructors and destructors
  203. Q59: When my base class's constructor calls a virtual function, why doesn't my
  204.    derived class's override of that virtual function get invoked?
  205. Q60: Does a derived class destructor need to explicitly call the base
  206.    destructor?
  207. SUBSECTION 12E: Inheritance -- Private and protected inheritance
  208. Q61: How do you express "private inheritance"?
  209. Q62: How are "private inheritance" and "composition" similar?
  210. Q63: Which should I prefer: composition or private inheritance?
  211. Q64: Should I pointer-cast from a "privately" derived class to its base
  212.    class?
  213. Q65: How is protected inheritance related to private inheritance?
  214. Q66: What are the access rules with "private" and "protected" inheritance?
  215.  
  216. SECTION 13: Abstraction
  217. Q67: What's the big deal of separating interface from implementation?
  218. Q68: How do I separate interface from implementation in C++ (like Modula-2)?
  219. Q69: What is an ABC ("abstract base class")?
  220. Q70: What is a "pure virtual" member function?
  221. Q71: How can I provide printing for an entire hierarchy of classes?
  222. Q72: When should my destructor be virtual?
  223. Q73: What is a "virtual constructor"?
  224.  
  225. ========== POSTING #3 ==========
  226.  
  227. SECTION 14: Style guidelines
  228. Q74: What are some good C++ coding standards?
  229. Q75: Are coding standards necessary?  Are they sufficient?
  230. Q76: Should our organization determine coding standards from our C
  231.    experience?
  232. Q77: Should I declare locals in the middle of a fn or at the top?
  233. Q78: What source-file-name convention is best? "foo.C"? "foo.cc"? "foo.cpp"?
  234. Q79: What header-file-name convention is best? "foo.H"? "foo.hh"? "foo.hpp"?
  235. Q80: Are there any lint-like guidelines for C++?
  236.  
  237. SECTION 15: Keys for Smalltalk programmers to learn C++
  238. Q81: Why does C++'s FAQ have a section on Smalltalk? Is this
  239.    Smalltalk-bashing?
  240. Q82: What's the difference between C++ and Smalltalk?
  241. Q83: What is "static typing", and how is it similar/dissimilar to Smalltalk?
  242. Q84: Which is a better fit for C++: "static typing" or "dynamic typing"?
  243. Q85: How can you tell if you have a dynamically typed C++ class library?
  244. Q86: How do you use inheritance in C++, and is that different from Smalltalk?
  245. Q87: What are the practical consequences of diffs in Smalltalk/C++
  246.    inheritance?
  247. Q88: Do you need to learn a "pure" OOPL before you learn C++?
  248. Q89: What is the NIHCL?  Where can I get it?
  249.  
  250. SECTION 16: Reference and value semantics
  251. Q90: What is value and/or reference semantics, and which is best in C++?
  252. Q91: What is "virtual data," and how-can / why-would I use it in C++?
  253. Q92: What's the difference between virtual data and dynamic data?
  254. Q93: Should I normally use pointers to freestore allocated objects for my data
  255.    members, or should I use "composition"?
  256. Q94: What are relative costs of the 3 performance hits associated with
  257.    allocating member objects from the freestore?
  258. Q95: Are "inline virtual" member fns ever actually "inlined"?
  259. Q96: Sounds like I should never use reference semantics, right?
  260. Q97: Does the poor performance of ref semantics mean I should pass-by-value?
  261.  
  262. ========== POSTING #4 ==========
  263.  
  264. SECTION 17: Linkage-to/relationship-with C
  265. Q98: How can I call a C function "f(int,char,float)" from C++ code?
  266. Q99: How can I create a C++ function "f(int,char,float)" that is callable by
  267.    my C code?
  268. Q100: Why's the linker giving errors for C/C++ fns being called from C++/C
  269.    fns?
  270. Q101: How can I pass an object of a C++ class to/from a C function?
  271. Q102: Can my C function access data in an object of a C++ class?
  272. Q103: Why do I feel like I'm "further from the machine" in C++ as opposed to
  273.    C?
  274.  
  275. SECTION 18: Pointers to member functions
  276. Q104: Is the type of "ptr-to-member-fn" different from "ptr-to-fn"?
  277. Q105: How can I ensure objects of my class are always created via "new" rather
  278.    than as locals or global/static objects?
  279. Q106: How do I pass a ptr to member fn to a signal handler, X event callback,
  280.    etc?
  281. Q107: Why am I having trouble taking the address of a C++ function?
  282. Q108: How do I declare an array of pointers to member functions?
  283.  
  284. SECTION 19: Container classes and templates
  285. Q109: How can I insert/access/change elements from a linked
  286.    list/hashtable/etc?
  287. Q110: What's the idea behind "templates"?
  288. Q111: What's the syntax / semantics for a "function template"?
  289. Q112: What's the syntax / semantics for a "class template"?
  290. Q113: What is a "parameterized type"?
  291. Q114: What is "genericity"?
  292.  
  293. SECTION 20: Nuances of particular implementations
  294. Q115: GNU C++ (g++) produces big executables for tiny programs; Why?
  295. Q116: Is there a yacc-able C++ grammar?
  296. Q117: What is C++ 1.2?  2.0?  2.1?  3.0?
  297.  
  298. SECTION 21: Miscellaneous technical and environmental issues
  299. SUBSECTION 21A: Miscellaneous technical issues:
  300. Q118: Why are classes with static data members getting linker errors?
  301. Q119: What's the difference between the keywords struct and class?
  302. Q120: Why can't I overload a function by its return type?
  303. Q121: What is "persistence"?  What is a "persistent object"?
  304. SUBSECTION 21B: Miscellaneous environmental issues:
  305. Q122: Is there a TeX or LaTeX macro that fixes the spacing on "C++"?
  306. Q123: Where can I access C++2LaTeX, a LaTeX pretty printer for C++ source?
  307. Q124: Where can I access "tgrind," a pretty printer for C++/C/etc source?
  308. Q125: Is there a C++-mode for GNU emacs?  If so, where can I get it?
  309. Q126: Where can I get OS-specific FAQs answered (e.g.,BC++,DOS,Windows,etc)?
  310. Q127: Why does my DOS C++ program says "Sorry: floating point code not
  311.    linked"?
  312. ==============================================================================
  313. SUBSECTION 1C: Nomenclature and Common Abbreviations
  314. ==============================================================================
  315.  
  316. Here are a few of the abbreviations/etc used in this article:
  317.  
  318.     term    meaning
  319.     ====    ===========
  320.     fn        function
  321.     fns        functions
  322.     param    parameter
  323.     ptr        pointer, a C/C++ construct declared by:  int * p;
  324.     ref        reference, a C++ construct declared by:  int & r;
  325.     OO        object-oriented
  326.     OOP        object-oriented programming
  327.     OOPL    object-oriented programming language
  328.     method    an alternate term for "member function"
  329.  
  330. ==============================================================================
  331. SECTION 2: How should I post something? (READ BEFORE POSTING)
  332. ==============================================================================
  333.  
  334. Q1: Which newsgroup should I post my questions?
  335.  
  336. Comp.lang.c++ is the best place to discuss the C++ language itself (e.g.,
  337. C++ code design, syntax, style).  Other newsgroups exist for discussion of
  338. topics which are specific to a particular system (e.g., MS Windows or UNIX)
  339. or topics which are not directly related to the C++ language (e.g., how to
  340. use your compiler).  Here's a list of some very active newsgroups and
  341. excerpts from their Frequently Asked Questions lists.  These excerpts
  342. should give you an idea of the type of topics frequently discussed there.
  343.  
  344.   comp.os.ms-windows.programmer.tools
  345.      This group is intended for discussions about the selection and use of
  346.      tools for Windows software development.
  347.   comp.os.ms-windows.programmer.misc
  348.      This group is for all other discussions about Windows software
  349.      development.
  350.   [There's one FAQ list for all the comp.os.ms-windows.programmer.* groups]
  351.      FAQ 5.7.1.  Accessing C++ classes in a DLL
  352.      FAQ 6.1.1.  A dialog as an MDI child window [with OWL]
  353.      FAQ 6.2.1.  Disabled menu choices become enabled [with MFC]
  354.      FAQ 8.1.5.  Using STRICT with windows.h
  355.      FAQ 10.  A programmer's bibliography
  356.  
  357.   comp.os.msdos.programmer
  358.      Much of the traffic is about language products (chiefly from Borland
  359.      and Microsoft).
  360.      FAQ 301. How can I read a character without [waiting for] the Enter key?
  361.      FAQ 412. How can I read, create, change, or delete the volume label?
  362.      FAQ 504. How do I configure a COM port and use it to transmit data?
  363.      FAQ 602. How can a C program send control codes to my printer?
  364.      FAQ 606. How can I find the Microsoft mouse position and button status?
  365.      FAQ 707. How can I write a TSR (terminate-stay-resident) utility?
  366.      FAQ B0. How can I contact [Borland, Microsoft]?
  367.      [note: this FAQ is not available at rtfm.mit.edu; it is at Simtel
  368.             (e.g., oak.oakland.edu) in /pub/msdos/info/faqp*.zip and Garbo
  369.             (garbo.uwasa.fi) in /pc/doc-net/faqp*.zip]
  370.   comp.os.msdos.programmer.turbovision [Borland's character-mode framework]
  371.  
  372.   comp.unix.programmer
  373.      FAQ 4.5)  How do I use popen() to open a process for reading AND writing?
  374.      FAQ 4.6)  How do I sleep() in a C program for less than one second?
  375.  
  376.   comp.unix.solaris (covers SunOS 4.x and Solaris)
  377.      FAQ 4)  Signal Primer
  378.      FAQ 5)  Waiting for Children to Exit
  379.  
  380.   gnu.g++.help
  381.      FAQ: Where can I find a demangler?
  382.      FAQ: Getting gcc/g++ binaries for Solaris 2.x
  383.      FAQ: What documentation exists for g++ 2.x?
  384.   gnu.g++.bug [bug reports for g++ -- see the g++ docs]
  385.  
  386.   comp.lang.c
  387.      FAQ 1.10: I'm confused.  NULL is guaranteed to be 0, but the null
  388.                pointer is not?
  389.      FAQ 2.3:  So what is meant by the "equivalence of pointers and
  390.                arrays" in C?
  391.      FAQ 4.2:  [Why doesn't "printf("%d\n," i++ * i++);" work?]
  392.      FAQ 7.1:  How can I write a function that takes a variable number
  393.                of arguments? [stdarg.h or varargs.h]
  394.      FAQ 10.4: How do I declare an array of pointers to functions returning
  395.                pointers to functions returning pointers to characters?
  396.  
  397. Also check out the newsgroups comp.graphics, comp.sources.wanted,
  398. comp.programming, and comp.object (its FAQ is an excellent introduction and
  399. overview of OOP terms and concepts).  Remember that comp.std.c++ is for
  400. discussion DIRECTLY related to the evolving ANSI/ISO C++ Standard (see more
  401. below). 
  402.  
  403. There's rarely a need to crosspost a question to one of the above
  404. newsgroups and comp.lang.c++ (readers in the system-specific newsgroups
  405. aren't programming in machine language, ya know).  It's bad netiquette to
  406. crosspost widely because your problem is "really important."  If you don't
  407. get an answer in the "right" newsgroup and feel you must post here, at
  408. least consider redirecting followups back to the appropriate newsgroup.
  409.  
  410. Before posting a question to any newsgroup you should read it's FAQ list.
  411. An answer to your question is likely to be there, saving you the time of
  412. posting and saving thousands of other people around the world the time of
  413. reading your question.  People answering a FAQ are likely to be annoyed for
  414. having to answer it for the umpteenth time, or they're likely to be giving
  415. you a wrong or incomplete answer since they haven't read the FAQ either.
  416.  
  417. Frequently Asked Questions lists are available 24-hours a day via anonymous
  418. ftp (rtfm.mit.edu in /pub/usenet/comp.what.ever) or e-mail server (send a
  419. message with the line "help" to mail-server@rtfm.mit.edu).  See the article
  420. "Introduction to the *.answers newsgroups" in the newsgroup news.answers or
  421. news.announce.newusers (which contains many other must-read articles) for
  422. more information.
  423.  
  424. ==============================================================================
  425.  
  426. Q2: How do I post a question about code that doesn't work correctly?
  427.  
  428. Here's some guidelines you should follow that will help people reading
  429. comp.lang.c++ help you with an answer to your programming problem.
  430.  
  431. 1. Please read the previous FAQ to make sure that your question is about the
  432.    C++ language and not a question about programming on your system (e.g.,
  433.    graphics, printers, devices, etc.) or using your compilation
  434.    environment (e.g., "the IDE crashes when I...," "how do you turn off
  435.    warnings about...," "how do I tell it to link my libraries").  If you
  436.    want to know why your virtual CmOk() function isn't being called in
  437.    your OWL program, your question is probably more appropriate in the
  438.    Windows programming newsgroup.  If you can write a small stand-alone
  439.    program which exhibits the same undesired compiler error or behavior
  440.    as your OWL program, by all means post here in comp.lang.c++ since C++
  441.    programmers using other systems could be of help.
  442.  
  443. 2. Be descriptive in the subject line.  "C++ problem" leaves a lot to the
  444.    imagination.  "Problem new'ing a multi-dimensional array" is good.
  445.    Refrain from exclamation points, cries for HELPPP, and the once funny
  446.    "SEX SEX SEX."  If you think the problem is specific to your compiler,
  447.    you might want to mention the compiler/version in the subject line.
  448.  
  449. 3. Post code that is complete and compilable.  It's extremely difficult
  450.    to debug or reconstruct a program from a human language description.
  451.    By "complete code" I mean that any types and functions used are
  452.    declared, headers are #include'd, etc.  Please strip the code down to
  453.    the bare essentials.  We don't need a program that does something
  454.    useful at run-time, or even links.  We just need to be able to
  455.    reproduce the undesired compiler error (possibly on a different
  456.    compiler).  By "compilable code" I mean that it doesn't contain a
  457.    bunch of uncommented ellipses or line numbers at the beginning of each
  458.    line:
  459.  
  460.     14:    #include <iostream.h>
  461.     15:    class Foo { ... };  // this is annoying
  462.  
  463.    Try to organize the code into one linear program instead of making us cut
  464.    out and create header files.  Be very careful if you are typing the code
  465.    into your article -- it's often difficult to tell whether something is a
  466.    typo or the real cause of the problem.  Try using your editor's
  467.    cut&paste or "insert file" feature instead.
  468.  
  469. 4. Mention what compiler, compiler version, and system you're using.  I
  470.    know, I just said that system-specific questions should go to a
  471.    system-specific newsgroup, but compiler information is often very
  472.    useful in diagnosing the problem: ("yeah, I remember Acme 1.2 having
  473.    lots of problems in this area").  It also warns other users of that
  474.    compiler about possible bugs.
  475.  
  476. 5. Show us the exact compiler and linker options and libraries you used
  477.    when building your program.
  478.  
  479. 6. List the exact error message and where the error was given.  "Virtual
  480.    functions don't work" doesn't tell us whether its a compile-, link-, or
  481.    run-time problem.  If the problem is at run-time, give a good
  482.    description of the behavior and any relevant information about your
  483.    system setup.
  484.  
  485. 7. Include a working e-mail address in your signature.  If the address in
  486.    given your article's "From:" line is not correct, please notify your
  487.    system administrator.  Until it is fixed, add a "Reply-To:" line to
  488.    your headers that uses your correct e-mail address.
  489.  
  490. 8. Please read the rest of this FAQ -- chances are your problem, or a
  491.    closely related problem, is discussed here.  Thank you and I hope these
  492.    suggestions help you find a solution to your problem.
  493.  
  494. ==============================================================================
  495. SECTION 3: Environmental/managerial issues
  496. ==============================================================================
  497.  
  498. Q3: What is OOP?  What is C++?
  499.  
  500. OO programming techniques are the best way we know of to develop large, complex
  501. software applications and systems.
  502.  
  503. C++ is an OO programming language.  C++ can be used both as an OOPL and simply
  504. "as a better C."  However if you use it "as a better C," don't expect to get
  505. the benefits of object-oriented programming.
  506.  
  507. OO hype: the software industry is "failing" to meet demands for large, complex
  508. software systems.  But this "failure" is actually due to our SUCCESSES: our
  509. successes have propelled users to ask for more.  Unfortunately we created a
  510. market hunger that the "structured" analysis, design and programming techniques
  511. couldn't satisfy.  This required us to create a better paradigm.
  512.  
  513. ==============================================================================
  514.  
  515. Q4: What are some advantages of C++?
  516.  
  517. GROWTH OF C++: C++ is by far the most popular OOPL.  The number of C++ users is
  518. doubling every 7.5 to 9 months.  Knowing C++ is a good resume-stuffer (but use
  519. it as an OOPL rather than just as a better C).
  520.  
  521. ENCAPSULATION: Hiding our data structures allows us to change one chunk of a
  522. system without breaking other chunks.  We provide our software chunks (we call
  523. them "classes") with safe interfaces.  Users of a chunk use its interface only.
  524. The relatively volatile "implementation" of this interface is "encapsulated"
  525. ("put into a capsule") to prevent users from becoming reliant on its temporary
  526. decisions.  In simple C, this was done by making a module's data "static", thus
  527. preventing another module from accessing our module's bits.
  528.  
  529. MULTIPLE INSTANCES: The typical C solution to encapsulation (see above) doesn't
  530. support multiple instances of the data (it's hard to make multiple instances of
  531. a module's "static" data).  If we needed multiple instances in C, we used a
  532. "struct" (but this doesn't support "encapsulation").  In C++, we can have both
  533. multiple instances and encapsulation via a "class": the "public" part of a
  534. class contains the class's interface (normally these are a special kind of
  535. function called a "member function"), and the "private" part of a class
  536. contains the class's implementation (typically these are where the bits live).
  537.  
  538. INLINE FUNCTION CALLS: In straight C, you can achieve "encapsulated structs" by
  539. putting a "void*" in a struct (the access functions use pointer casts).  This
  540. forfeits type safety, and also imposes a function call to access even trivial
  541. fields of the struct (if you allowed direct access to the struct's fields, the
  542. underlying data structure would be difficult to change since too many chunks
  543. would RELY on it being the "old" way).  Function call overhead is small, but
  544. can add up.  C++ classes allow function calls to be expanded "inline," so you
  545. have: the 1) safety of encapsulation, 2) convenience of multiple instances, 3)
  546. speed of direct access.  Furthermore the parameter types of these inline
  547. functions are checked by the compiler, an improvement over C's #define macros.
  548.  
  549. OVERLOADING OPERATORS: C++ lets you overload the standard operators on a class,
  550. which lets users exploit their intuition (e.g., "myString + yourString" might
  551. do string concatenation, "myDate++" might increment the date, "z1 * z2" might
  552. multiply complex numbers z1 and z2, "a[i]" might access the "i"th element of
  553. the "linked list" called "a", etc.  You can even have "smart pointers" that
  554. could "point" to a disk record or wherever ("x = *p" could "dereference" such a
  555. pointer, which could seek to the location on disk where p "points" and return
  556. its value").  This allows users to program in the language of the problem
  557. domain rather than in the language of the machine.
  558.  
  559. INHERITANCE: We still have just scratched the surface.  In fact, we haven't
  560. even gotten to the "object-oriented" part yet!  Suppose you have a Stack data
  561. type with operations push, pop, etc.  Suppose you want an InvertableStack,
  562. which is "just like" Stack except it also has an "invert" operation.  In "C"
  563. style, you'd have to either (1) modify the existing Stack module (trouble if
  564. "Stack" is being used by others), or (2) copy Stack into another file and text
  565. edit that file (results in lots of code duplication, another chance to break
  566. something tricky in the Stack part of InvertableStack, and especially twice as
  567. much code to maintain).  C++ provides a much cleaner solution: inheritance.
  568. You say "InvertableStack inherits everything from Stack, and InvertableStack
  569. adds the invert operation."  Done.  Stack itself remains "closed" (untouched,
  570. unmodified), and InvertableStack doesn't duplicate the code for push/pop/etc.
  571.  
  572. POLYMORPHISM AND DYNAMIC BINDING: The real power of OOP isn't just inheritance,
  573. but is the ability to pass an InvertableStack around as if it actually were a
  574. Stack.  This is "safe" since (in C++ at least) the is-a relation follows public
  575. inheritance (i.e., a InvertableStack is-a Stack that can also invert itself).
  576. Polymorphism and dynamic binding are easiest to understand from an example, so
  577. here's a "classic": a graphical draw package might deal with Circles, Squares,
  578. Rectangles, general Polygons, and Lines.  All of these are Shapes.  Most of the
  579. draw package's functions need a "Shape" parameter (as opposed to some
  580. particular kind of shape like Square).  E.g., if a Shape is picked by a mouse,
  581. the Shape might get dragged across the screen and placed into a new location.
  582. Polymorphism and dynamic binding allow the code to work correctly even if the
  583. compiler only knows that the parameter is a "Shape" without knowing the exact
  584. kind of Shape it is.  Furthermore suppose the "pick_and_drag(Shape*) function
  585. just mentioned was compiled on Tuesday, and on Wednesday you decide to add the
  586. Hexagon shape.  Strange as it sounds, pick_and_drag() will still work with
  587. Hexagons, even though the Hexagon didn't even exist when pick_and_drag() was
  588. compiled!!  (it's not really "amazing" once you understand how the C++ compiler
  589. does it -- but it's still very convenient!)
  590.  
  591. ==============================================================================
  592.  
  593. Q5: Who uses C++?
  594.  
  595. Lots and lots of companies and government sites.  Lots.
  596.  
  597. Statistically, 5 people became new C++ programmers while you read the words of
  598. the previous FAQ.
  599.  
  600. ==============================================================================
  601.  
  602. Q6: Are there any C++ standardization efforts underway?
  603.  
  604. Yes; ANSI (American) and ISO (International) groups are working closely with
  605. each other.  The ANSI-C++ committee is called "X3J16".  The ISO C++ standards
  606. group is called "WG21".  The major players in the ANSI/ISO C++ standards
  607. process includes just about everyone:
  608.  
  609. AT&T, IBM, DEC, HP, Sun, MS, Borland, Zortech, Apple, OSF, etc ad nauseum.
  610. About 70 people attend each meeting.  People come from USA, UK, Japan, Germany,
  611. Sweden, Denmark, France, ... (all have "local" committees sending official
  612. representatives and conducting "local" meetings).
  613.  
  614. ==============================================================================
  615.  
  616. Q7: Where can I get a copy of the latest ANSI-C++ draft standard?
  617.  
  618. ANSI standards and/or drafts are NOT available in machine readable form.  There
  619. is NOT an "ftp" site that has a copy.  You can get a paper copy ($25) from:
  620.  
  621.     X3 Secretariat
  622.     CBEMA
  623.     1250 I Street NW
  624.     Suite 200
  625.     Washington, DC  20005
  626.     202-626-5738
  627.  
  628. Ask for the latest version of "Working Paper for Draft Proposed American
  629. National Standard for Information Systems -- Programming Language C++."
  630.  
  631. ==============================================================================
  632.  
  633. Q8: Is C++ backward compatible with ANSI-C?
  634.  
  635. Almost.
  636.  
  637. C++ is as close as possible to compatible with C, but no closer.  In practice,
  638. the major difference is that C++ requires prototypes, and that "f()" declares a
  639. function that takes no parameters (in C, "f()" is the same as "f(...)").  There
  640. are some very subtle differences as well, like sizeof('x') is equal to
  641. sizeof(char) in C++ but is equal to sizeof(int) in C.  Also, C++ puts structure
  642. "tags" in the same namespace as other names, whereas C requires an explicit
  643. "struct" (the "typedef struct Fred Fred" technique still works, but is
  644. redundant in C++).
  645.  
  646. ==============================================================================
  647.  
  648. Q9: How long does it take to learn C++?
  649.  
  650. Companies like Paradigm Shift, Inc. successfully teach standard industry "short
  651. courses", where we compress a university semester course into one 40hr work
  652. week.  However true mastery takes experience; there's no substitute for time.
  653. Hands-on projects are essential, since they allow concepts to "gel."
  654.  
  655. It takes 6-12 months to become proficient in C++/OOP.  Less if the developers
  656. have easy access to a "local" body of experts, more if there isn't a "good"
  657. general purpose C++ class library available.  To become one of these experts
  658. who can mentor others takes around 3 years.
  659.  
  660. Some people never make it.  You don't have a chance unless you are teachable
  661. and have personal drive.  As a bare minimum on "teachability," you have to be
  662. able to admit when you've been wrong for years and years.  As a bare minimum on
  663. "drive," you've got to be willing to put in some extra hours (changing the way
  664. you think [a paradigm shift] is a LOT more painful than learning a few new
  665. facts).
  666.  
  667. ==============================================================================
  668. SECTION 4: Basics of the paradigm
  669. ==============================================================================
  670.  
  671. Q10: What is a class?
  672.  
  673. The fundamental building block of OO software.
  674.  
  675. A class defines a data type, much like a struct would be in C.  In a computer
  676. science sense, a type consists of both a set of states AND a set of operations
  677. which transition between those states.  Thus "int" is a "type" because it has
  678. both a set of states AND it has operations like "add two ints" or "int*int,"
  679. etc.  In exactly the same way, a "class" provides a set of (usually public)
  680. operations, and a set of (usually non-public) data bits representing the
  681. abstract values that instances of the type can have.  From a C language
  682. perspective, a class is a struct whose members default to "private".
  683.  
  684. Think of "int" as a class that has methods called "operator++", etc.
  685.  
  686. ==============================================================================
  687.  
  688. Q11: What is an object?
  689.  
  690. A region of storage with associated semantics.
  691.  
  692. After the declaration "int i;" we say that "i is an object of type int."  In
  693. C++/OOP, "object" usually means "an instance of a class."  Thus a class defines
  694. the behavior of possibly many objects (instances).
  695.  
  696. ==============================================================================
  697.  
  698. Q12: What is a reference?
  699.  
  700. An alias (an alternate name) for an object.
  701.  
  702. References are frequently used for pass-by-reference:
  703.  
  704.     void swap(int& i, int& j)
  705.     {
  706.       int tmp = i;
  707.       i = j;
  708.       j = tmp;
  709.     }
  710.  
  711.     main()
  712.     {
  713.       int x, y;
  714.       //...
  715.       swap(x,y);
  716.     }
  717.  
  718. Here "i" and "j" are aliases for main's "x" and "y" respectively.  In other
  719. words, "i" IS "x" -- not a pointer to "x", nor a copy of "x", but "x" itself.
  720. Anything you do to "i" gets done to "x", and vise versa.
  721.  
  722. Underneath it all, references are typically implemented by pointers.  The
  723. effect is as if you used the C style pass-by-pointer, but the "&" is moved from
  724. the caller into the callee, and you eliminate all the "*"s.
  725.  
  726. ==============================================================================
  727.  
  728. Q13: What happens if you assign to a reference?
  729.  
  730. You change the referrent (the object to which the reference refers).
  731.  
  732. Remember: the reference IS the referrent, so changing the reference changes the
  733. referrent (a reference is an "Lvalue" [something that can appear on the
  734. "L"eft-hand-side of an assignment statement] for the referrent).
  735.  
  736. This insight can be pushed a bit farther by allowing references to be RETURNED.
  737. This allows function calls on the left hand side of an assignment statement,
  738. which is useful with operator overloading.
  739.  
  740. ==============================================================================
  741.  
  742. Q14: How can you reseat a reference to make it refer to a different object?
  743.  
  744. No way.
  745.  
  746. Unlike a pointer, once a reference is bound to an object, it can NOT be
  747. "reseated" to another object.  The reference itself isn't an object (it has no
  748. address; taking the address of a reference gives you the address of the
  749. referrent; remember: the reference IS its referrent).
  750.  
  751. You can't separate the reference from the referent.
  752.  
  753. ==============================================================================
  754.  
  755. Q15: When should I use references, and when should I use pointers?
  756.  
  757. Use references when you can, and pointers when you have to.
  758.  
  759. References are usually preferred over ptrs whenever you don't need "reseating"
  760. (see previous FAQ).  This usually means that references are most useful in a
  761. class's public interface.  References typically appear on the skin of an
  762. object, and pointers on the inside.
  763.  
  764. The exception to the above is where a function's parameter or return value
  765. needs a "sentinel" reference.  This is usually best done by returning/taking a
  766. pointer, and giving the NULL pointer this special significance (references
  767. should always alias objects, not a dereferenced NULL ptr).
  768.  
  769. NOTE: Old line C programmers sometimes don't like references since they provide
  770. reference semantics that isn't explicit in the caller's code.  After some C++
  771. experience, however, one quickly realizes this is a form of information hiding,
  772. which is an asset rather than a liability.  E.g., programmers should write code
  773. in the language of the problem rather than the language of the machine.
  774.  
  775. ==============================================================================
  776.  
  777. Q16: What's the deal with inline functions?
  778.  
  779. An inline function is a function whose code gets inserted into the caller's
  780. code stream.  Like a macro, inline functions improve performance by avoiding
  781. the overhead of the call itself and (especially!) by the compiler being able to
  782. optimize THROUGH the call ("procedural integration").  Unlike macros, inline
  783. functions avoid infamous macro errors by evaluating all arguments exactly once
  784. (the "call" is semantically like a regular function call, only faster).  Also
  785. unlike macros, argument types are checked, and necessary conversions are
  786. performed correctly (macros are bad for your health; don't use them unless you
  787. absolutely have to).
  788.  
  789. Beware that overuse of inline functions can cause code bloat, which can in
  790. turn have a negative performance impact in paging environments.
  791.  
  792. They are declared by using the "inline" keyword when the function is defined:
  793.  
  794.     inline void f(int i, char c) { /*...*/ }
  795.  
  796. or by including the function definition itself within a class:
  797.  
  798.     class Fred {
  799.     public:
  800.       void f(int i, char c) { /*...*/ }
  801.     };
  802.  
  803. or by defining the member function as "inline" outside the class:
  804.  
  805.     class Fred {
  806.     public:
  807.       void f(int i, char c);
  808.     };
  809.  
  810.     inline void Fred::f(int i, char c) { /*...*/ }
  811.  
  812. ==============================================================================
  813. SECTION 5: Constructors and destructors
  814. ==============================================================================
  815.  
  816. Q17: What's the deal with constructors?
  817.  
  818. Constructors build objects from dust.
  819.  
  820. Constructors are like "init functions"; they turn a pile of arbitrary bits into
  821. a living object.  Minimally they initialize internally used fields.  They may
  822. also allocate resources (memory, files, semaphores, sockets, etc).
  823.  
  824. "ctor" is a typical abbreviation for constructor.
  825.  
  826. ==============================================================================
  827.  
  828. Q18: How can I make a constructor call another constructor as a primitive?
  829.  
  830. No way.
  831.  
  832. Dragons be here: if you call another constructor, the compiler initializes a
  833. temporary local object; it does NOT initialize "this" object.  You can combine
  834. both constructors by using a default parameter, or you can share their common
  835. code in a private "init()" member function.
  836.  
  837. ==============================================================================
  838.  
  839. Q19: What's the deal with destructors?
  840.  
  841. A destructor gives an object its last rites.
  842.  
  843. Destructors are used to release any resources allocated by the object.  E.g., a
  844. Lock class might lock a semaphore, and the destructor will release that
  845. semaphore.  The most common example is when the constructor uses "new", and the
  846. destructor uses "delete".
  847.  
  848. Destructors are a "prepare to die" method.  They are often abbreviated "dtor".
  849.  
  850. ==============================================================================
  851. SECTION 6: Operator overloading
  852. ==============================================================================
  853.  
  854. Q20: What's the deal with operator overloading?
  855.  
  856. It allows users of your classes to use intuitive syntax.
  857.  
  858. Operator overloading allows C/C++ operators to have user-defined meanings on
  859. user-defined types (classes).  They're syntactic sugar for function calls:
  860.  
  861.     class Fred {
  862.     public:
  863.       //...
  864.     };
  865.  
  866.     #if 0
  867.       Fred add(Fred, Fred);        //without operator overloading
  868.       Fred mul(Fred, Fred);
  869.     #else
  870.       Fred operator+(Fred, Fred);    //with operator overloading
  871.       Fred operator*(Fred, Fred);
  872.     #endif
  873.  
  874.     Fred f(Fred a, Fred b, Fred c)
  875.     {
  876.       #if 0
  877.         return add(add(mul(a,b), mul(b,c)), mul(c,a));  //without...
  878.       #else
  879.         return a*b + b*c + c*a;                         //with...
  880.       #endif
  881.     }
  882.  
  883. ==============================================================================
  884.  
  885. Q21: What operators can/cannot be overloaded?
  886.  
  887. Most can be overloaded. The only C operators that can't be are "." and "?:"
  888. (and "sizeof," which is technically an operator).  C++ adds a few of its own
  889. operators, most of which can be overloaded except "::" and ".*".
  890.  
  891. Here's an example of the subscript operator (it returns a reference).  First
  892. withOUT operator overloading:
  893.  
  894.     class Array {
  895.     public:
  896.       #if 0
  897.         int& elem(unsigned i) { if (i>99) error(); return data[i]; }
  898.       #else
  899.         int& operator[] (unsigned i) { if (i>99) error(); return data[i]; }
  900.       #endif
  901.     private:
  902.       int data[100];
  903.     };
  904.  
  905.     main()
  906.     {
  907.       Array a;
  908.  
  909.       #if 0
  910.         a.elem(10) = 42;
  911.         a.elem(12) += a.elem(13);
  912.       #else
  913.         a[10] = 42;
  914.         a[12] += a[13];
  915.       #endif
  916.     }
  917.  
  918. ==============================================================================
  919.  
  920. Q22: Can I create a "**" operator for "to-the-power-of" operations?
  921.  
  922. Nope.
  923.  
  924. The names of, precedence of, associativity of, and arity of operators is fixed
  925. by the language.  There is no "**" operator in C++, so you cannot create one
  926. for a class type.
  927.  
  928. If you're in doubt, consider that "x ** y" is the same as "x * (*y)" (in other
  929. words, the compiler assumes "z" is a pointer).  Besides, operator overloading
  930. is just syntactic sugar for function calls.  Although this particular syntactic
  931. sugar can be very sweet, it doesn't add anything fundamental.  I suggest you
  932. overload "pow(base,exponent)" (a double precision version is in <math.h>).
  933.  
  934. BTW: operator^ can work, except it has the wrong precedence and associativity.
  935.  
  936. ==============================================================================
  937. SECTION 7: Friends
  938. ==============================================================================
  939.  
  940. Q23: What is a "friend"?
  941.  
  942. Something to allow your class to grant access to another class or function.
  943.  
  944. Friends can be either functions or other classes.  A class grants access
  945. privileges to its friends.  Normally a developer has political and technical
  946. control over both the friends and methods of a class (else you need permission
  947. from the owner of the other pieces when you want to update your class).
  948.  
  949. ==============================================================================
  950.  
  951. Q24: Do "friends" violate encapsulation?
  952.  
  953. If they're used properly, they actually ENHANCE encapsulation.
  954.  
  955. You often need to split a class in half when the two halves will have different
  956. numbers of instances or different lifetimes.  In these cases, the two halves
  957. usually need direct access to each other (the two halves USED to be in the same
  958. class, so you haven't INCREASED the number of methods that have direct access
  959. to a data structure; you've simply MOVED some of those methods).  The safest
  960. way to implement this is to make the two halves friends of each other.
  961.  
  962. If you use friends like just described, you'll keep private things private.  In
  963. a naive effort to avoid using friendship in situations like the above, many
  964. people actually destroy encapsulation by either using public data (grotesque!),
  965. or by making the data accessible between the halves via public get/set methods.
  966. Having a public get and set method for a private datum is only ok when the
  967. private datum "makes sense" from outside the class (from a user's perspective).
  968. In many cases, these get/set methods are almost as bad as public data: they
  969. hide (only) the NAMES of the private data members, but they don't hide the
  970. existence of the private data members.
  971.  
  972. Similarly, if you use friend functions as a syntactic variant of a class's
  973. public access functions, they don't violate encapsulation any more than a
  974. member function violates encapsulation.  In other words, a class's friends and
  975. members ARE the encapsulation barrier, as defined by the class itself.
  976.  
  977. ==============================================================================
  978.  
  979. Q25: What are some advantages/disadvantages of using friend functions?
  980.  
  981. They provide a degree of freedom in the interface design options.
  982.  
  983. Member fns and friend fns are equally privileged (100% vested).  The major
  984. difference is that a friend function is called like "f(x)", while a member is
  985. called like "x.f()".  Thus friend fns allow the class's designer to select
  986. the syntax that is deemed most readable, which lowers maintenance costs.
  987.  
  988. The major disadvantage of friend functions is that they require an extra line
  989. of code when you want dynamic binding.  To get the effect of a virtual friend,
  990. the friend function should call a hidden (usually "protected:") virtual member
  991. fn; e.g., "void f(Base& b) { b.do_f(); }".  Derived classes override the hidden
  992. virtual member function ("void Derived::do_f()"), NOT the friend function.
  993.  
  994. ==============================================================================
  995.  
  996. Q26: What does it mean that "friendship is neither inherited nor transitive"?
  997.  
  998. The privileges of friendship aren't inherited: derived classes of a friend
  999. aren't necessarily friends (I may declare you as my friend, but that doesn't
  1000. mean I necessarily trust your kids).  If class "Base" declares "f()" to be a
  1001. friend, "f()" doesn't have any automatic special access rights to the extra
  1002. stuff declared in derived class, "Derived."
  1003.  
  1004. The privileges of friendship aren't transitive: friends of a friend class
  1005. aren't necessarily friends of the original class (a friend of a friend isn't
  1006. necessarily a friend).  E.g., if class "Fred" declares class "Wilma" as a
  1007. friend, and class "Wilma" declares "f()" as a friend, "f()" doesn't necessarily
  1008. have any special access rights to "Fred".
  1009.  
  1010. ==============================================================================
  1011.  
  1012. Q27: Should my class declare a member function or a friend function?
  1013.  
  1014. Use a member when you can, and a friend when you have to.
  1015.  
  1016. Sometimes friends are syntactically better (e.g., in class "Fred", friend fns
  1017. allow the "Fred" param to be second, while members require it to be first).
  1018. Another good use of friend functions are the binary infix arithmetic operators
  1019. (e.g., "aComplex + aComplex" probably should be defined as a friend rather than
  1020. a member, since you want to allow "aFloat + aComplex" as well; recall members
  1021. don't allow promotion of the left hand arg, since that would change the class
  1022. of the object that is the recipient of the member function invocation).
  1023.  
  1024. In other cases, choose a member function over a friend function.
  1025.  
  1026. ==============================================================================
  1027. SECTION 8: Input/output via <iostream.h> and <stdio.h>
  1028. ==============================================================================
  1029.  
  1030. Q28: How can I provide printing for a "class Fred"?
  1031.  
  1032. Provide a friend operator<<:
  1033.  
  1034.     class Fred {
  1035.     public:
  1036.       friend ostream& operator<< (ostream& o, const Fred& fred)
  1037.         { return o << fred.i; }
  1038.       //...
  1039.     private:
  1040.       int i;    //just for illustration
  1041.     };
  1042.  
  1043. We use a friend rather than a member since the "Fred" parameter is second
  1044. rather than first.  Input is similar, but the signature is:
  1045.  
  1046.     istream& operator>> (istream& i, Fred& fred);
  1047.                                   // ^^^^^------- not "const Fred& fred"!
  1048.  
  1049. ==============================================================================
  1050.  
  1051. Q29: Why should I use <iostream.h> instead of the traditional <stdio.h>?
  1052.  
  1053. Increase type safety, reduce errors, improve performance, allow extensibility,
  1054. and provide subclassability.
  1055.  
  1056. Printf is arguably not broken, and scanf is perhaps livable despite being error
  1057. prone, however both are limited with respect to what C++ I/O can do.  C++ I/O
  1058. (using "<<" and ">>") is, relative to C (using "printf()" and "scanf()"):
  1059.  
  1060.  * Type safe -- type of object being I/O'd is known statically by the compiler,
  1061.    rather than via dynamically tested via "%" fields.
  1062.  
  1063.  * Less error prone -- redundant info increases the chance of errors.  C++ I/O
  1064.    has no redundant "%" tokens to get right.
  1065.  
  1066.  * Faster -- printf is an "interpreter" of a tiny language whose constructs
  1067.    mainly include "%" fields; it uses these fields to select the right
  1068.    formatting primitive at run-time.  C++ I/O picks these routines statically
  1069.    based on actual types of the args.  This improves performance.
  1070.  
  1071.  * Extensible -- the C++ I/O mechanism allows new user-defined types to be
  1072.    added without breaking existing code (imagine the chaos if everyone was
  1073.    simultaneously adding new incompatible "%" fields to printf and scanf?!).
  1074.  
  1075.  * Subclassable -- ostream and istream (the C++ replacements for FILE*) are
  1076.    real classes, and hence subclassable.  This means you can have other user
  1077.    defined things that look and act like streams, yet that do whatever strange
  1078.    and wonderful things you want.  You automatically get to use the zillions of
  1079.    lines of I/O code written by users you don't even know, and they don't need
  1080.    to know about your "extended stream" class.
  1081.  
  1082. --
  1083. Marshall Cline
  1084. --
  1085. Marshall P. Cline, Ph.D. / Paradigm Shift Inc / PO Box 5108 / Potsdam NY 13676
  1086. cline@sun.soe.clarkson.edu / 315-353-6100 / FAX: 315-353-6110
  1087.